<?php
class Media extends Module {
    public function upload() {
        
        $cdn = tos_get_config('cdn');
        $path = tos_http_post('path');
        $caption = tos_http_post('img_caption');
        
        $sys_path = $cdn['dir'] . '/' . $path;
        
        $img_file = $this->_upload_img($sys_path, $caption);
        if ($img_file) {
            
            //$url = 'http://' . $cdn['url'] . '/' . $path . '/' . $img_file;
            $src = $path . '/' . $img_file;
            $text = "<input type=\"text\" id=\"result\" value=\"$src\" />";
            
            return new View_text($text);
        }
    }
    
    private function _upload_img($path, $name = '') {
        if ( ! is_dir($path)) {
            return false;
        }
        
        if ( ! isset($_FILES['img_input_file'])) {
            return false;
        }
        
        $file = $_FILES['img_input_file'];
        $type = $file['type'];
        if ( ($type == "image/jpeg") || ($type == "image/pjpeg") || ($type == "image/png")) {
          if ($file["error"] > 0) {
            echo "Return Code: " . $file["error"] . "<br />";
            return false;
          }
          
          $name = trim($name);
          $oname = $file['name'];
          if ( ! empty($name)) {
              $name = tos_clean_url_segment($name);
              $name .= '.' . pathinfo($oname, PATHINFO_EXTENSION);
          } else {
              $name = $oname;
          }
          $full_file = $path . '/' . $name;
          if (file_exists($full_file)) {
              $name = time() . '-' . $name;
              $full_file = $path . '/' . $name;
          }
          if (move_uploaded_file($file["tmp_name"], $full_file)) {
                return $name;
            }
        }
        return false;

    }
}
?>